package com.google.code.virtualhockey.vhx.client;

import com.google.code.virtualhockey.vhx.client.res.VhxResources;
import com.google.code.virtualhockey.vhx.client.srvcom.CommandDispatcher;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.mvp4g.client.Mvp4gModule;

/**
 * Entry point for VHX' GWT based UI.
 */
public class VhxEntryPoint implements EntryPoint {

  public static final String       SESSION_COOKIE         = "ACSID";
  public static final String       SECURE_SESSION_COOKIE  = "SACSID";
  public static final String       GWT_DEV_URL_SUFFIX     = "gwt.codesvr=127.0.0.1:9997";

  private static CommandDispatcher d_dispatcher;

  /**
   * Returns the central command dispatcher.
   */
  public static CommandDispatcher dispatcher()
  {
    if ( d_dispatcher == null )
      d_dispatcher = new CommandDispatcher( "/command" );

    return d_dispatcher;
  }

  /**
   * Initialises the VHX client side web application.
   */
  @Override
  public void onModuleLoad() {
    VhxResources.INSTANCE.style().ensureInjected();
    Mvp4gModule module = (Mvp4gModule) GWT.create( Mvp4gModule.class );
    module.createAndStartModule();
    RootLayoutPanel.get().add( (Widget) module.getStartView() );
  }

  /**
   * Returns the current security token that can be used for server side command dispatching.
   */
  public static String getSecurityToken() {
    String strToken = Cookies.getCookie( SESSION_COOKIE );

    if ( strToken == null )
      strToken = Cookies.getCookie( SECURE_SESSION_COOKIE );

    Window.alert( "Cookie: " + strToken );
    
    return strToken;
  }

  /*
   * ====================================================================================================
   * Access to _vhx preset variables.
   */

  public static native String getUserEmail() /*-{
    return $wnd._vhx['user'];
  }-*/;

  public static native boolean isAdmin() /*-{
    return $wnd._vhx['is_admin'];
  }-*/;

  public static native boolean isGaeProdMode() /*-{
    return $wnd._vhx['is_gae_prod'];
  }-*/;

  public static String getLoginUrl() {
    if ( GWT.isProdMode() )
      return getInternalLoginUrl();
    else
      return getInternalLoginUrl() + "%3F" + GWT_DEV_URL_SUFFIX;
  }

  private static native String getInternalLoginUrl() /*-{
    return $wnd._vhx['login_url'];
  }-*/;

  public static String getLogoutUrl() {
    if ( GWT.isProdMode() )
      return getInternalLogoutUrl();
    else
      return getInternalLogoutUrl() + "%3F" + GWT_DEV_URL_SUFFIX;
  }

  private static native String getInternalLogoutUrl() /*-{
    return $wnd._vhx['logout_url'];
  }-*/;
}
